
import wx
import CaseControlView
import wx.lib.agw.customtreectrl as CT
import os
import cPickle
import project.project as project
from validator import validate_significance_level 
import epiguilib
import case_control.epiCaseConCalcOO as case_control_one_to_one 
import case_control.epiCaseConCalcOA as case_control_one_to_all
import webbrowser

ONE_TO_ONE_MODE = 0
ONE_TO_ALL_MODE = 1


class SelectAnalysisDlg(CaseControlView.SelectAnalysisDialog):
	def __init__(self, callback):
		CaseControlView.SelectAnalysisDialog.__init__(self, parent=None)	
		self.callback = callback
		prj = project.get_current_project()
		analysis_folders = os.listdir(prj.epistasis_output_directory)
		print analysis_folders
		self.analysis_list.Clear()
		self.analysis_list.InsertItems(analysis_folders, 0)
		
	def OnItemSelected(self, event):
		self.on_btn.Enable(True)
		
	def OnCancel(self, event):
		self.Destroy()
		
	def OnConfirmSelection(self, event):
		self.callback(self.analysis_list.GetStringSelection())
		self.Hide()
		
# Implementing CaseControl
class CaseControl( CaseControlView.CaseControl ):
	def __init__( self, parent, size=(800,600)):
		
		#self.analysis_name = "" 
		self.analysis_name = ""	
		self.path_to_case_control_files = ""
		
		#if not self.analysis_name:
		#	return
		#print self.analysis_name
		
		CaseControlView.CaseControl.__init__( self, parent)
		
		
		self.class_checklist.Bind(CT.EVT_TREE_ITEM_CHECKED, self.OnClassItemChecked )
		#self.files_list.Bind(wx.EVT_LISTBOX, self.OnCaseControlFileSelected)
		self.phenotype_checklist.Clear()
		self.class_checklist.Clear()
		
		#if dlg.ShowModal() != wx.ID_OK:
		#	self.Destroy()
		#	return  
		
		dlg = SelectAnalysisDlg(self.OnAnalysisSelected)
		
		dlg.Show()
		self.Enable(False)
		
		#dlg.Show()
			
	def OnAnalysisSelected(self, analysis_name):
		print "callback"
		self.analysis_name = analysis_name
		prj = project.get_current_project()
		self.analysis_root_dir = os.path.join(prj.epistasis_output_directory, self.analysis_name)
		self.path_to_case_control_files = os.path.join(self.analysis_root_dir, "epi_res_pkl")
		
		self.populate_lists()
		self.Enable(True)
	
	def populate_lists(self):
		# load files 
		self.analysis_title.SetLabel(self.analysis_name)
		self.GetTopLevelParent().Layout()
		files = os.listdir(self.path_to_case_control_files)
		files.sort()
		self.class_checklist.Clear()
		self.class_checklist.add_items(files)
#		
		#print files
		#self.files_list.Clear()
		#self.files_list.InsertItems(files,0)
		
#	def OnCaseControlFileSelected(self, event):
#		file_name = event.GetEventObject().GetStringSelection()
#		if not file_name: 
#			return
#		file_path = os.path.join(self.path_to_case_control_files, file_name) 
#		f = open(file_path)
#		output_data = cPickle.load(f)
#		traits = [trait["trait_name"] for trait in output_data["epistasis_data"]]
#		#self.phenotype_checklist.Clear()
#		self.phenotype_checklist.add_phenotypes(traits)
#		
	def validate_input(self):
		
		sig_level_str = self.significance_level.GetValue()
		try:
			validate_significance_level(sig_level_str)
		except Exception, e:
			return False, str(e)

		if self.mode_radiobox.GetSelection() == ONE_TO_ONE_MODE:
			num_checked_classes = 0
			for item in self.class_checklist.GetRootItem().GetChildren():
				if item.IsChecked():
					num_checked_classes += 1
			if num_checked_classes < 2:
				return False, "Select at least 2 classes in one-on-one mode."
			
		num_checked_phenotypes = 0
		for item in self.phenotype_checklist.GetRootItem().GetChildren():
			if item.IsChecked():
				num_checked_phenotypes += 1
		
		if not num_checked_phenotypes:
			return False, "Please select a phenotype."
			
		return True, "Input is valid"
		
	def OnClassItemChecked(self, event):
		#item = event.GetItem()
		print "item toggled", event.GetItem().IsChecked(), event.GetItem().GetText()
		
		pkl_file = event.GetItem().GetText()
		pkl_file_path = os.path.join(self.path_to_case_control_files, pkl_file) 
		f = open(pkl_file_path)
		output_data = cPickle.load(f)
		traits = [trait["trait_name"] for trait in output_data["epistasis_data"]]
		self.phenotype_checklist.Clear()
		self.phenotype_checklist.add_items(traits)
#		
#		mode = self.mode_radiobox.GetSelection()
#		
#		#checked = 
#		
#		if mode == ONE_TO_ALL_MODE:
#			print "one-to-all"
#			
#			if event.GetItem().IsChecked():
#				checked_item = event.GetItem()	
#				all_items = self.phenotype_checklist.GetRootItem().GetChildren()
#				self.phenotype_checklist.SelectItem(checked_item, True)
#				#self.phenotype_checklist.SelectAll()
#				#print all_items
#				
#				for i in all_items:
#					if checked_item != i:
#						#self.phenotype_checklist.SelectItem(i, True)
#						i.Enable(False)
#						i.Check()
#						
#				self.Refresh()
#						
#			
#			else:
#				#checked = self.phenotype_checklist.GetChecked()
#				all_items = self.phenotype_checklist.GetRootItem().GetChildren()
#				unchecked_item = event.GetItem()	
#				self.phenotype_checklist.SelectItem(unchecked_item, False)
#				
#				for i in all_items:
#					i.Enable(True)
#					i.Check(False)
#					
#				self.Refresh()
#				
#				#self.phenotype_checklist.SetCheckedStrings([])
#		else:
#			
#			#num_checked = 0
#			checked_items = []
#			all_items = self.phenotype_checklist.GetRootItem().GetChildren()
#			for i in all_items:
#				if i.IsChecked():
#					checked_items.append(i)
#			
#			if len(checked_items) == 2:
#				
#				for j in all_items:
#					if j not in checked_items:
#						#self.phenotype_checklist.SelectItem(i, True)
#						j.Enable(False)
#						#j.Check()
#			else:
#				for j in all_items:
#					j.Enable(True)
#			
#			
#		self.Refresh()
#	
#	def OnItemChecked(self, event):
#		#item = event.GetItem()
#		print "item toggled", event.GetItem().IsChecked()
#		
#		mode = self.mode_radiobox.GetSelection()
#		
#		#checked = 
#		
#		if mode == ONE_TO_ALL_MODE:
#			print "one-to-all"
#			
#			if event.GetItem().IsChecked():
#				checked_item = event.GetItem()	
#				all_items = self.phenotype_checklist.GetRootItem().GetChildren()
#				self.phenotype_checklist.SelectItem(checked_item, True)
#				#self.phenotype_checklist.SelectAll()
#				#print all_items
#				
#				for i in all_items:
#					if checked_item != i:
#						#self.phenotype_checklist.SelectItem(i, True)
#						i.Enable(False)
#						i.Check()
#						
#				self.Refresh()
#						
#			
#			else:
#				#checked = self.phenotype_checklist.GetChecked()
#				all_items = self.phenotype_checklist.GetRootItem().GetChildren()
#				unchecked_item = event.GetItem()	
#				self.phenotype_checklist.SelectItem(unchecked_item, False)
#				
#				for i in all_items:
#					i.Enable(True)
#					i.Check(False)
#					
#				self.Refresh()
#				
#				#self.phenotype_checklist.SetCheckedStrings([])
#		else:
#			
#			#num_checked = 0
#			checked_items = []
#			all_items = self.phenotype_checklist.GetRootItem().GetChildren()
#			for i in all_items:
#				if i.IsChecked():
#					checked_items.append(i)
#			
#			if len(checked_items) == 2:
#				
#				for j in all_items:
#					if j not in checked_items:
#						#self.phenotype_checklist.SelectItem(i, True)
#						j.Enable(False)
#						#j.Check()
#			else:
#				for j in all_items:
#					j.Enable(True)
#			
#			
#		self.Refresh()
#		
	#def Clean(self):
	def OnModeSelection( self, event ):
		print "mode changed", event.GetSelection()
		self.class_checklist.UnselectAll()
		self.phenotype_checklist.Clear()
		
		all_items = self.class_checklist.GetRootItem().GetChildren()
		for i in all_items:
			i.Enable(True)
			i.Check(False)
		self.Refresh()
			
	def OnCancel( self, event ):
		self.GetTopLevelParent().remove_page_tab(self)
		
		
	def OnStart( self, event ):
		
		validated, msg = self.validate_input()
		
		if not validated:
			dlg = wx.MessageDialog(self, msg, "Error.", wx.ICON_ERROR)
			dlg.ShowModal()
			return False
		
		sig_level_str = self.significance_level.GetValue()
		signicance_level = float(sig_level_str)
		
		
		all_class_pkl_items = self.class_checklist.GetRootItem().GetChildren()
		
		checked_pkl_files = []
		
		for item in all_class_pkl_items:
			if item.IsChecked():
				absolute_path = os.path.join(self.path_to_case_control_files, item.GetText())
				checked_pkl_files.append(absolute_path)
		
		checked_phenotypes = []
		
		for p in self.phenotype_checklist.GetRootItem().GetChildren():
			if p.IsChecked():
				checked_phenotypes.append(p.GetText())
		
		#phenotypes = [i.GetText() for i in self.phenotype_checklist.GetRootItem().GetChildren()] 
		analysis_name = self.analysis_name
		mode = self.mode_radiobox.GetSelection()
		
		
		if mode == ONE_TO_ONE_MODE:
			args = (checked_pkl_files, signicance_level, checked_phenotypes, analysis_name, self.analysis_root_dir)
			print args
			epiguilib.run_in_thread_with_progressbar(case_control_one_to_one.start, args=args, 
													callback=self.OnCaseControlFinished, host_gui_object=self, msg="Running case control.")
		else:
			all_class_pkl_files = [os.path.join(self.path_to_case_control_files, item.GetText()) for item in all_class_pkl_items]
			args = (checked_pkl_files, all_class_pkl_files, signicance_level, checked_phenotypes, analysis_name, self.analysis_root_dir)
			print args
			epiguilib.run_in_thread_with_progressbar(case_control_one_to_all.start, args=args, 
													callback=self.OnCaseControlFinished, host_gui_object=self, msg="Running case control.")
		

	def OnCaseControlFinished(self, event):
		dlg = wx.MessageDialog(self, "Case control analysis is complete. Result files are in \n %s\n\nGo to result folder?" % self.analysis_root_dir, "Case control finished", wx.YES_NO |
							   wx.YES_DEFAULT | wx.ICON_QUESTION)		
		if dlg.ShowModal() == wx.ID_YES:
			webbrowser.open(self.analysis_root_dir)
			
			
if __name__ == "__main__":
	app = wx.App(False)  # Create a new app, don't redirect stdout/stderr to a window.
    #project.open_project("/home/benjamin/Dokumenter/epiprojects/my_project_testshit/my_project_testshit.epiprj")
	frame = wx.Frame(None, wx.ID_ANY, "Hello World", size=(1000,800)) # A Frame is a top-level window.
    
    #panel = wx.Panel(frame, wx.ID_ANY) # A Frame is a top-level window.)
    

	w = CaseControl(frame)
	frame.Show()
    
	app.MainLoop()

	
